import React, { useEffect, useRef, useState } from 'react';
import { Modal, Button, message } from 'antd'
import {
  fileUpload
} from '@/services/register';

import styles from './index.module.less'

const Camera = ({
  title,
  btnName = '证件拍照',
  initSrc = null,
  // 不关闭
  noClose = false,
  onChangeImage,
  // 是否可以编辑
  isEdit = true,
}) => {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);

  const [isOpen, setIsOpen] = useState<boolean>(false);

  const [imgSrc, setImgSrc] = useState(initSrc || null)

  const [fileData, setFile] = useState(null)

  async function openVideo() {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');

    // const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
    // console.log('mediaStream :>> ', mediaStream);
    navigator.mediaDevices.getUserMedia({ video: true }).then((stream) => {
      console.log('stream :>> ', stream);
      video.srcObject = stream;
    })
      .catch((error) => {
        console.error('Error accessing camera:', error);
      });
    // Capture photo
    video.addEventListener('loadedmetadata', () => {
      setIsOpen(true)
      // canvas.width = video.videoWidth;
      // canvas.height = video.videoHeight;
      // context.drawImage(video, 0, 0, canvas.width, canvas.height);
      // // Save the photo or perform any other desired operations with the captured image
      // const photoData = canvas.toDataURL('image/png');
    });
  }


  //将base64转换为blob
  function dataURLtoBlob(dataurl) {
    let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  //将blob转换为file
  function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
  }

  const handleCapture = async () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    const context = canvas.getContext('2d');

    // // Access the camera
    // navigator.mediaDevices.getUserMedia({ video: true })
    //   .then((stream) => {
    //     video.srcObject = stream;
    //   })
    //   .catch((error) => {
    //     console.error('Error accessing camera:', error);
    //   });
    // const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
    // console.log('mediaStream :>> ', mediaStream);
    // video.srcObject = mediaStream;
    // Capture photo
    // video.addEventListener('loadedmetadata', async () => {
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    // Save the photo or perform any other desired operations with the captured image
    const photoData = canvas.toDataURL('image/png');
    setImgSrc(photoData)

    console.log('photoData :>> ', photoData);
    //调用
    let blob = dataURLtoBlob(photoData);
    let file = blobToFile(blob, '');
    setFile(file);
    // console.log('file :>> ', file, base64Data);
    const formData = new FormData();
    formData.append("file", file);
    return;
    const res = await fileUpload(formData);
    if (res?.resultCode === "00000000") {
      message.success(res?.message)
      onChangeImage && onChangeImage(`${UpUrl}${res?.data}`)
      colseModal()
    } else {
      message.error(res?.message)
    }

    // console.log('res :>> ', res.data);
    // });
    // setIsFrist(false)

  };


  async function onColse() {
    const video = videoRef.current;
    const videoTrack = video?.srcObject?.getVideoTracks()[0];
    // /* const mediaStream = await */ navigator.mediaDevices.getUserMedia({ video: false });
    await videoTrack?.stop();
    video?.srcObject?.getTracks().forEach(track => track.stop());
    videoRef.current.srcObject = null;
    console.log('videoTrack :>> ', videoTrack);
  }


  function showModal() {
    openVideo()
    setIsOpen(true);
  }

  async function colseModal() {
    await onColse()
    setImgSrc(null)
    setTimeout(() => {
      setIsOpen(false);
    }, 500)
  }

  async function onUpLoad() {
    const formData = new FormData();
    formData.append("file", fileData);
    const res = await fileUpload(formData);
    if (res?.resultCode === "00000000") {
      message.success(res?.message)
      onChangeImage && onChangeImage(`${UpUrl}${res?.data}`)
      if (noClose) {
        await onColse()
        setIsOpen(false);
      } else {
        colseModal()
      }
    } else {
      message.error(res?.message)
    }
  }


  return (
    <div className={styles.wrapper}>
      <>
        <div className={styles.wrap}>
          <div className={styles.videoBox} style={{width:'293px'}}>
            <div className={styles.name}>{title}取景区</div>
            <video
              className={styles.video}
              ref={videoRef}
              autoPlay
            // controls
            /* style={{ display: 'none' }} */
            />
          </div>

          <div className={styles.canvasBox}>
            <canvas ref={canvasRef} />
          </div>
          <div className={styles.captureBox}>
            <div className={styles.imgBox}>
              <div className={styles.name}>成像区</div>
              <div className={styles.captureImg}>
                {imgSrc && <img src={imgSrc} alt='' />}
              </div>
            </div>
            {isEdit && !isOpen && <div className={styles.captureBtn} onClick={openVideo}>打开摄像头</div>}
            {
              isEdit && isOpen &&
              <>
                <div className={styles.captureBtn} onClick={handleCapture}>拍照</div>
                <div className={styles.captureBtn} onClick={onUpLoad}>确认并上传</div>
              </>
            }
          </div>
        </div>
        {/* <Button onClick={openVideo}>打开摄像头</Button>
          <Button onClick={onColse}>关闭摄像头</Button> */}
      </>
    </div>
  );
};

export default Camera;